package com.wjv.example.springboot.base.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * <p>Title: CorsConfig</p>
 *
 * @author wjv
 * @since 2021/7/30 13:40
 */
@Configuration
public class CorsConfig {

    /**
     * 当前跨域请求最大有效时长。这里默认30天
     */
    private final long MAX_AGE = 30 * 24 * 60 * 60;


    private CorsConfiguration buildConfig() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 1 设置访问源地址
        config.addAllowedOrigin("*");
        // 2 设置访问源请求头
        config.addAllowedHeader("*");
        // 3 设置访问源请求方法
        config.addAllowedMethod("*");
        config.setAllowCredentials(true);
        config.setMaxAge(MAX_AGE);
        return config;
    }

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 4 对接口配置跨域设置
        source.registerCorsConfiguration("/**", buildConfig());
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}
